package com.bdqn.controller;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    private Logger logger = Logger.getLogger(LoginController.class);
    @Resource
    private SysUserService sysUserService;

    // 定义用户会话键的常量
    public static final String USER_SESSION_KEY = "USER_SESSION";

    @RequestMapping(value = "/toLogin")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session) throws Exception {
        SysUser sysUser = sysUserService.login(account, password);

        if (null!= sysUser) {
            // 使用自定义常量设置会话中的用户对象
            session.setAttribute(USER_SESSION_KEY, sysUser);
        } else {
            request.setAttribute("error", "用户名和密码不正确");
            return "login";
        }
        return "redirect:/sys/toMain";
    }

    @RequestMapping("/logout")
    public String login(HttpSession session) {
        // 使用自定义常量移除会话中的用户对象
        session.removeAttribute(USER_SESSION_KEY);
        return "login";
    }

    @RequestMapping("/sys/toMain")
    public String toMain() {
        return "frame";
    }
}
